package test.jusfy.com.myapplication;

import android.content.Context;
import android.content.res.AssetManager;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by Administrator on 2017/9/13 0013.
 */

public class SQLDataBaseManager {

    public static final String TAG = "SQLDataBaseManager";
    //数据库存储路径
    public static final String filePath = "data/data/test.jusfy.com.myapplication/midi_temp.db";
    public static final String pathSrc = "data/data/test.jusfy.com.myapplication";

    SQLiteDatabase database;
    private static SQLDataBaseManager instance;

    public static synchronized SQLDataBaseManager getInstance(){
        if(instance==null){
            instance = new SQLDataBaseManager();
        }
        return instance;
    }

    public SQLiteDatabase openDataBase(Context context){
        File jhPath = new File(filePath);
        //查看数据库文件是否存在
        if(jhPath.exists()){
            Log.d(TAG, "存在数据库");
            return SQLiteDatabase.openOrCreateDatabase(jhPath,null);
        }else{
            //不存在先创建文件夹
            File path = new File(pathSrc);
            if(path.mkdir()){
                Log.i(TAG, "创建成功");
            }else{
                Log.i(TAG,"创建失败");
            }
            try {
                //得到资源
                AssetManager am = context.getAssets();
                //得到数据库的输入流
                InputStream is = am.open("midi_temp.db");
                Log.i("test", is+"");
                FileOutputStream fos = new FileOutputStream(jhPath);
                Log.i("test", "fos="+fos);
                Log.i("test", "jhPath="+jhPath);
                //创建byte数组  用于1KB写一次
                byte[] buffer=new byte[1024];
                int length = 0;
                while ((length=is.read(buffer))>0){
                    Log.i("test", "得到");
                    fos.write(buffer,0,length);
                }
                fos.flush();
                fos.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
            //假设没有这个数据库  我们已经把他写到SD卡上了。然后在运行一次这种方法 就能够返回数据库了
            return openDataBase(context);
        }
    }

}
